/*
 * Copyright 2010 Nicolas Martignole.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
 * required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
 * OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 */

import grails.util.Environment
import org.letouilleur.celerio.Account
import org.letouilleur.celerio.Role
import org.letouilleur.celerio.Document
import org.letouilleur.celerio.AccountRole
import org.letouilleur.celerio.CivilityEnum
import org.letouilleur.celerio.Address
import org.letouilleur.celerio.Book
import org.letouilleur.celerio.Legacy
import org.letouilleur.celerio.RequestMap

/**
 * BootStrap scripts that is executed when grails starts.
 * @author Nicolas Martignole.
 */
class BootStrap {
    def authenticateService

  def init = {servletContext ->
    switch (Environment.current) {
      case Environment.DEVELOPMENT:
        createAccount()
        createRole()
        createDocument()
        createAccountRole()
        createAddress()
        createBook()
        createLegacy()
        createRequestMapURLs()
        break;
    }
  }
  def destroy = {
  }

  void createAccount() {
    // I have to specify an empty accountId else Grails won't create entries... It sucks

    def a = new Account(username: "nicmarti", email: "nic@test.fr", enabled: true, firstName: "Nicolas", lastName: "Martignole", birthDate: new Date() - 10, civility: CivilityEnum.MR)
    a.setPassword(authenticateService.encodePassword("test123"))
    a.save(flush: true)
    if (a.hasErrors()) {
      println "Unable to create an Account  "
      a.errors.each { println it }
    }
    def fr=new Account(username: "framiere",  email: "framiere@jaxio.com", enabled: true, firstName: "Florent", lastName: "Ramière", birthDate: new Date() - 12, civility: CivilityEnum.MR)
    fr.setPassword(authenticateService.encodePassword("test123"))
    fr.save(flush:true)

    def nr=new Account(username: "nromanetti", email: "nromanetti@jaxio.com", enabled: true, firstName: "Nicolas", lastName: "Romanetti", birthDate: new Date() - 12, civility: CivilityEnum.MR)
    nr.setPassword(authenticateService.encodePassword("test123"))
    nr.save(flush:true)
  }

  void createRole() {
    def role = new Role(nameLocale: "Administrateur", authority: "ROLE_ADMIN")
    role.save(flush: true)
    if (role.hasErrors()) {
      println "Unable to create a Role due to " + role.errors
    }

    // Now we create roles without checkink if it was a success or not
    new Role(nameLocale: "Utilisateur", authority: "ROLE_USER").save()
    new Role(nameLocale: "Validateur", authority: "ROLE_VALIDATOR").save()

  }

  void createDocument() {
    def d = new Document(documentContentType: "text/plain", documentSize: 1024, documentFileName: "sampleBootstrap.txt", documentBinary: "test".getBytes(), version: 1)
    d.save(flush: true)
    if (d.hasErrors()) {
      println "Unable to create a Document due to " + d.errors
    }
    def d2 = new Document(documentContentType: "text/plain", documentSize: 1024, documentFileName: "docNicolas.txt", documentBinary: "doc de nicolas".getBytes(), version: 1)
    d2.account = Account.findByUsername("nicmarti")
    d2.save()
  }

  void createAccountRole() {
    def ar = new AccountRole(account: Account.findByUsername("nicmarti"), role: Role.get(1))
    ar.save(flush: true)
    if (ar.hasErrors()) {
      println "Unable to link Account1 to Role1 " + ar.errors
    }
    new AccountRole(account: Account.findByUsername("nicmarti"), role: Role.get(2)).save()
    new AccountRole(account: Account.findByUsername("framiere"), role: Role.get(2)).save()
    new AccountRole(account: Account.findByUsername("nromanetti"), role: Role.get(2)).save()
    new AccountRole(account: Account.findByUsername("nicmarti"), role: Role.get(3)).save()
  }

  void createAddress() {
    def adr = new Address(city: "Paris", streetName: "120 Bd Saint Martin")
    adr.save(flush: true)
    if (adr.hasErrors()) {
      println "Unable to create an Address due to " + adr.errors
    }
    def nicAdd = new Address(streetName: "60 Clos des Cascades", city: "Noisy-le-Grand")
    nicAdd.save()

    def u1 = Account.findByUsername("nicmarti")
    if (!u1) {
      throw new RuntimeException("Account not found")
    }
    u1.setAddress(nicAdd)
    u1.save()

    def u2 = Account.findByUsername("framiere")
    u2.setAddress(adr)
    u2.save()

    def u3 = Account.findByUsername("nromanetti")
    u3.setAddress(adr)
    u3.save()


  }

  void createBook() {
    def book = new Book(bookId: 1, title: "Grails in Action", account: Account.findByUsername("nicmarti"), numberOfPages: 376)
    book.save(flush: true)
    if (book.hasErrors()) {
      println "Unable to create a book linked to an Account due to " + book.errors
    }
    new Book(title: "French Cuisine", account: Account.get(1), numberOfPages: 500).save()
    new Book(title: "Scala for dummies", account: Account.get(2), numberOfPages: 146).save()
    new Book(title: "Java EE 6", account: Account.get(3), numberOfPages: 456).save()
    new Book(title: "Lift !", numberOfPages: 206).save()

  }

  void createLegacy() {
    def legacy1 = new Legacy(extraInfo: "Test legacy", code: "c1", dept: 91, name: "Essonne")
    legacy1.save()
  }

  void createRequestMapURLs() {
    // Protect access to document controller
    // Always put a star at the end of the pattern (see http://grails.org/AcegiSecurity%20Plugin%20-%20Securing%20URLs)
    new RequestMap(url: "/", configAttribute: "IS_AUTHENTICATED_ANONYMOUSLY").save()
    new RequestMap(url: "/login/auth", configAttribute: "IS_AUTHENTICATED_ANONYMOUSLY").save()
    new RequestMap(url: "/js/**", configAttribute: "IS_AUTHENTICATED_ANONYMOUSLY").save()
    new RequestMap(url: "/css/**", configAttribute: "IS_AUTHENTICATED_ANONYMOUSLY").save()
    new RequestMap(url: "/images/**", configAttribute: "IS_AUTHENTICATED_ANONYMOUSLY").save()
    new RequestMap(url: "/plugins/**", configAttribute: "IS_AUTHENTICATED_ANONYMOUSLY").save()
    new RequestMap(url: "/**", configAttribute: "IS_AUTHENTICATED_REMEMBERED").save()
    new RequestMap(url: "/document*", configAttribute: "ROLE_ADMIN").save()
    new RequestMap(url: "/account*", configAttribute: "ROLE_ADMIN").save()
    new RequestMap(url: "/book*", configAttribute: "ROLE_USER").save()

  }
} 